//
//  ScreenViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/15.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "ScreenViewController.h"
#import "ScreenTableViewCell.h"
#import "PositionModel.h"
#import <AMapLocationKit/AMapLocationKit.h>

#define AMPKey  @"5afdf7bc67e5d636b95c710fa6b85430"

@interface ScreenViewController ()
<UITableViewDataSource,UITableViewDelegate,AMapLocationManagerDelegate>
{
    UITableView * _tableView;
    NSMutableArray * _dataSource;
    NSMutableArray * flagArr;
    
    NSMutableArray * _dataArr;
    CGFloat totleW;
    
    NSMutableArray * selectedBtnArr;
    
    //
    ScreenModel * myModel;
    
    NSString * lat;
    NSString * lng;
}
@property (nonatomic, strong) AMapLocationManager *locationManager;

@end

@implementation ScreenViewController
#pragma mark - 视图的生命周期
-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];

//    AppDelegate * app = [UIApplication sharedApplication].delegate;
//    [app.viewController isHiddenCustomTabBarByBoolean:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    lat = @"";
    lng = @"";
    [self main];
    [self addItems];
    //[self addBackItem];
    self.navigationItem.title = @"筛选";
   // [self addNavgationBar];
    [self gaode];
    
    // Do any additional setup after loading the view.
}
-(void)main
{
    myModel = [[ScreenModel alloc]init];
    myModel.type = @"comp";
    myModel.keyword = @"";
    myModel.industry = @"";
    myModel.near = @"1";
    myModel.yqlh = @"0";
    myModel.page = @"1";
    myModel.pnum = @"10";
    myModel.lng = @"";
    myModel.lat = @"";
    
    _dataSource = [[NSMutableArray alloc]init];
    [_dataSource addObjectsFromArray:@[@"附近",@"优企排名"]];
    flagArr = [[NSMutableArray alloc]init];
    [flagArr addObjectsFromArray:@[@"0",@"0"]];
    selectedBtnArr = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 63, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = UIColorFromRGB(0xf1f3f2);
    [_tableView registerNib:[UINib nibWithNibName:@"ScreenTableViewCell" bundle:nil] forCellReuseIdentifier:@"ScreenTableViewCell"];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self requestData];
}
-(void)gaode
{
    //高德地图
    [AMapLocationServices sharedServices].apiKey = AMPKey;
    
    self.locationManager = [[AMapLocationManager alloc]init];
    self.locationManager.delegate = self;
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer];
    
    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == 2)
            {
                return;
            }
        }
        
        NSString * latt = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
        NSString * logg = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
        
        lat = [latt substringToIndex:latt.length-2];
        lng = [logg substringToIndex:logg.length-2];
        
        
    }];
    
}

-(void)requestData
{
    [U76HONet selectedTypeReadWithtype:@"6" fid:@"0" code:@"0" andDataBlock:^(NSArray *arr) {
        NSLog(@"获取行业分类的数据获取成功了");
        _dataArr = [[NSMutableArray alloc]init];
//        [_dataArr addObjectsFromArray:@[@"全部",@"互联网",@"文化/传媒",@"计算机软件",@"法律/教育/翻译",@"金融/保险",@"网络/通讯",@"客服/淘宝",@"行政/文秘",@"房产/建筑/物业管理",@"IT/运维/技术支持",@"物流/仓库",@"其它"]];
        [_dataArr addObjectsFromArray:arr];
        _tableView.tableFooterView = [self createMainViewwithData:_dataArr];

    }];
}
#pragma mark - _tableViewDelgate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ScreenTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ScreenTableViewCell"];
    cell.firstLab.text = _dataSource[indexPath.row];
    cell.isSelected = flagArr[indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 0) {
//        [flagArr replaceObjectAtIndex:0 withObject:@"1"];
//        [flagArr replaceObjectAtIndex:1 withObject:@"0"];
//        myModel.near = @"1";
//        myModel.yqlh = @"0";
//    }
//    else
//    {
//        [flagArr replaceObjectAtIndex:1 withObject:@"1"];
//        [flagArr replaceObjectAtIndex:0 withObject:@"0"];
//        myModel.near = @"0";
//        myModel.yqlh = @"1";
//    }
    if ([flagArr[indexPath.row] isEqualToString:@"1"]) {
        [flagArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
    }
    else
    {
        [flagArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
    }
    [_tableView reloadData];
}
#pragma mark - createMainView
-(UIView *)createMainViewwithData:(NSArray *)dataArr
{
    CGFloat w = SCREEN_WIDTH-SIZETO6W(20)*2;
    int jj = 0;
    
    for (int i = 0; i<dataArr.count; i++) {
        PositionModel * model = dataArr[i];

        NSString * str = model.typenames;
        CGFloat tempW = [str widthOfSize:20]+SIZETO6W(36);
        totleW = totleW+tempW+SIZETO6W(15);
        if (totleW<=w) {
            
        }
        else
        {
            jj = jj+1;
            totleW = tempW+SIZETO6W(15);
        }
    }
    totleW = 0;
    //view
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SIZETO6H(10)+SIZETO6H(17)+20+SIZETO6H(21)+40 + jj*(SIZETO6H(15)+40)+SIZETO6H(50)+40+SIZETO6H(20)+SIZETO6H(100))];
    view.backgroundColor = UIColorFromRGB(0xf1f3f2);
    
    //subView
    UIView * subView = [[UIView alloc]initWithFrame:CGRectMake(0, SIZETO6H(10), SCREEN_WIDTH, view.height-SIZETO6H(10)-SIZETO6H(50)-40-SIZETO6H(100))];
    subView.backgroundColor = UIColorFromRGB(0xFFFFFF);
    [view addSubview:subView];
    
    //titleLab
    UILabel * titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, SIZETO6H(17), SCREEN_WIDTH, 20)];
    titleLab.text = @"行业分类";
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = UIColorFromRGB(0x333944);
    [subView addSubview:titleLab];

    int j = 0;
    for (int i = 0; i<dataArr.count; i++) {
        PositionModel * model = dataArr[i];
        
        NSString * str = model.typenames;
        CGFloat tempW = [str widthOfSize:20]+SIZETO6W(36);
        totleW = totleW+tempW+SIZETO6W(15);
        if (totleW<=w) {
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(SIZETO6W(20)+totleW-tempW-SIZETO6W(15),titleLab.bottom + SIZETO6H(21)+j*(40+SIZETO6H(15)), tempW, 40);
            [btn setTitle:model.typenames forState:UIControlStateNormal];
            [btn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(selectedBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            btn.backgroundColor = [UIColor whiteColor];
            btn.layer.masksToBounds = YES;
            btn.layer.cornerRadius = 20;
            btn.layer.borderWidth = 1.0f;
            btn.tag = i+10;
            btn.layer.borderColor = [UIColorFromRGB(0x59b130)CGColor];
            [selectedBtnArr addObject:btn];
            [subView addSubview:btn];
            if (i == 0) {
                [btn setBackgroundColor:UIColorFromRGB(0x6ec844)];
                [btn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];

            }
        }
        else
        {
            
            j = j+1;
            totleW = tempW+SIZETO6W(15);
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setTitle:model.typenames forState:UIControlStateNormal];
            [btn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(selectedBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [selectedBtnArr addObject:btn];
            btn.layer.masksToBounds = YES;
            btn.layer.cornerRadius = 20;
            btn.tag = i+10;
            btn.frame = CGRectMake(SIZETO6W(20), titleLab.bottom + SIZETO6H(21)+j*(40+SIZETO6H(15)), tempW, 40);
            btn.layer.borderWidth = 1.0f;
            btn.layer.borderColor = [UIColorFromRGB(0x59b130)CGColor];
            btn.backgroundColor = [UIColor whiteColor];
            [subView addSubview:btn];
        }
    }
    
    UIButton * clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    clearBtn.frame = CGRectMake((SCREEN_WIDTH-115)/2, subView.bottom+SIZETO6H(50), 115, 40);
    [clearBtn setTitle:@"清除筛选" forState:UIControlStateNormal];
    [clearBtn addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
    [clearBtn setTitleColor:UIColorFromRGB(0x6ec844) forState:UIControlStateNormal];
    clearBtn.layer.masksToBounds = YES;
    clearBtn.layer.borderColor = [UIColorFromRGB(0X6E844)CGColor];
    clearBtn.layer.borderWidth = 1.0f;
    clearBtn.layer.cornerRadius = 5;
    [view addSubview:clearBtn];
    
    return view;
}
#pragma mark - btn的点击事件们
-(void)selectedBtnAction:(UIButton *)btn
{
    for (UIButton * b in selectedBtnArr) {
        if (btn == b) {
            [b setBackgroundColor:UIColorFromRGB(0x6ec844)];
            PositionModel * model = _dataArr[btn.tag-10];
            myModel.industry = model.Ids;
            [b setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
        }
        else
        {
            [b setBackgroundColor:UIColorFromRGB(0xffffff)];
//            btn.layer.borderWidth = 1.0f;
            [b setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
        }
    }
    
    
    
    
    
    if ([[flagArr objectAtIndex:0] isEqualToString:@"1"]) {
        myModel.near = @"1";
    }
    else
    {
        myModel.near = @"0";
    }
    if ([myModel.near isEqualToString:@"1"]) {
        myModel.lng = lng;
        myModel.lat = lat;
    }
    else
    {
        myModel.lng = @"";
        myModel.lat = @"";
    }
    
    //
    if ([[flagArr objectAtIndex:1] isEqualToString:@"1"]) {
        myModel.yqlh = @"1";
    }
    else
    {
        myModel.yqlh = @"0";
    }
    
    
    
    _screenmodelBlock(myModel);
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)clearAction:(UIButton *)btn
{
    myModel.type = @"comp";
    myModel.keyword = @"";
    myModel.industry = @"";
    myModel.near = @"1";
    myModel.yqlh = @"0";
    myModel.page = @"1";
    myModel.pnum = @"10";
    myModel.lng = @"";
    myModel.lat = @"";
    
    [flagArr replaceObjectAtIndex:0 withObject:@"0"];
    [flagArr replaceObjectAtIndex:1 withObject:@"0"];
    
    for (UIButton * b in selectedBtnArr) {
        [b setBackgroundColor:UIColorFromRGB(0xffffff)];
        [b setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    }
    
    [_tableView reloadData];
    
    [Singleton alerSendMessage:@"清除完成"];
    
}
#pragma mark - AddItems
-(void)addItems
{
    UIButton * shaiXuanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shaiXuanBtn.frame = CGRectMake(0,0, 60, 50);
    shaiXuanBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [shaiXuanBtn setTitle:@"完成" forState:UIControlStateNormal];
    [shaiXuanBtn addTarget:self action:@selector(shaiXuanBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [shaiXuanBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:shaiXuanBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}
-(void)shaiXuanBtnAction:(UIButton *)btn
{
    
    
    if ([[flagArr objectAtIndex:0] isEqualToString:@"1"]) {
        myModel.near = @"1";
    }
    else
    {
        myModel.near = @"0";
    }
    if ([myModel.near isEqualToString:@"1"]) {
        myModel.lng = lng;
        myModel.lat = lat;
    }
    else
    {
        myModel.lng = @"";
        myModel.lat = @"";
    }
    
    //
    if ([[flagArr objectAtIndex:1] isEqualToString:@"1"]) {
        myModel.yqlh = @"1";
    }
    else
    {
        myModel.yqlh = @"0";
    }
    
    
    
    _screenmodelBlock(myModel);
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
